package com.gxks.lhs.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启预处理和后处理的权限检
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SysUserDetailsService userDetailsService;

    @Autowired
    private SysAdminDetailsService adminDetailsService;
    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    @Autowired
    private NotLoginPoint notLoginPoint;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors()
                .configurationSource(corsConfigurationSource()) // 添加CORS配置
                .and()
                .authorizeRequests()
                .antMatchers("/demo/**", "/restful-api/*", "/img/*").permitAll()
                .antMatchers("/restful-api/ad/**", "/restful-api/area/**", "/restful-api/evaluation/queryBySellerId", "/restful-api/category/list", "/restful-api/goods/getGoods", "/restful-api/goods/getGoodsList", "/restful-api/goods/list").permitAll()
//                .antMatchers("/**/**").permitAll()
                .antMatchers("/authenticate", "/restful-api/user/register", "/restful-api/user/getRegCode").permitAll()
                .antMatchers("/restful-api/goods//hotSearch", "/restful-api/goods/search").permitAll()
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .apply(new JwtConfigurer(jwtTokenProvider))
                .and()
                .logout().logoutSuccessUrl("/")
                .and()
                .exceptionHandling().authenticationEntryPoint(notLoginPoint)
                .and()
                .headers().frameOptions().disable();

    }


    /**
     * 配置认证管理器构建器，用于设置用户详情服务和密码编码器。
     *
     * @param auth 认证管理器构建器，用于配置认证流程。
     * @throws Exception 如果配置过程中发生错误，则抛出异常。
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 为普通用户配置用户详情服务和密码编码器
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
        // 为管理员配置用户详情服务和密码编码器
        auth.userDetailsService(adminDetailsService).passwordEncoder(passwordEncoder());
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
//        configuration.setAllowedOrigins(Arrays.asList("http://localhost:5173","http://127.0.0.1:5173"));
//        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }


}
